package net.brucecooper.mindmapgadget.server;

import java.io.IOException;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

@SuppressWarnings("serial")
public class FreemindDownloadServlet extends UploadDownloadServlet {
//	private int dumpNode(Element parentNode, JSONObject model, int id, int indent) throws JSONException {
//		Element newNod = parentNode.getOwnerDocument().createElement("node");
//		newNod.setAttribute("CREATED", Long.toString(System.currentTimeMillis()));
//		newNod.setAttribute("MODIFIED", Long.toString(System.currentTimeMillis()));
//		newNod.setAttribute("ID", "Link"+ id);
//		newNod.setAttribute("TEXT", model.getString("n"));
//		parentNode.appendChild(newNod);
//		id++;
//		if (model.has("c")) {
//			JSONArray children = model.getJSONArray("c");
//			for (int i = 0; i < children.length(); i++) {
//				id = dumpNode(newNod, children.getJSONObject(i), id, indent+1);
//			}
//		}
//		return id;
//	}

    @Override
    protected String convertToResult(String contents) throws IOException {
//        try {
//            JSONObject model = new JSONObject(contents);
//            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
//            Document doc = db.newDocument();
//            
//            Element root = doc.createElement("map");
//            root.setAttribute("version", "0.8.1");
//            doc.appendChild(root);
//            
//            Transformer tx = TransformerFactory.newInstance().newTransformer();
//            tx.setOutputProperty(OutputKeys.INDENT, "yes");
//            
//            dumpNode(root, model, 0, 0);
//            
//            StringWriter sw = new StringWriter();
//            
//            tx.transform(new DOMSource(doc), new StreamResult(sw));
//            
//            return sw.toString();
//        } catch (Exception e) {
//            throw new IOException("Couldn't parse model parameter", e);
//        }
        return contents;
    }

    @Override
    protected String getResultContentType() {
        return "application/freemind";
    }
}
